<!-- pages/cardManage/cardManage.vue -->
<template>
  <view class="card-manage-container">
    <!-- 操作栏 -->
    <view class="operation-bar">
      <uni-search-bar 
        placeholder="搜索卡片名称" 
        v-model="searchKey"
        @confirm="loadData(true)"
        cancel-button="none"
      />
      <view class="filter-row">
        <picker @change="typeFilterChange" :value="filterType" :range="cardTypes">
          <view class="filter-btn">
            {{ cardTypes[filterType] }}
            <uni-icons type="arrowdown" size="14" color="#666"/>
          </view>
        </picker>
        <button class="add-btn" @tap="showEditForm(null)">+ 新建卡片</button>
      </view>
    </view>

    <!-- 数据统计 -->
    <scroll-view class="stats-scroll" scroll-x>
      <view class="stats-card">
        <text class="stats-value">{{ total }}</text>
        <text class="stats-label">总卡片数</text>
      </view>
      <view class="stats-card">
        <text class="stats-value">{{ activeCount }}</text>
        <text class="stats-label">已启用</text>
      </view>
      <view class="stats-card">
        <text class="stats-value">{{ virtualCount }}</text>
        <text class="stats-label">虚拟卡</text>
      </view>
    </scroll-view>

    <!-- 卡片列表 -->
    <scroll-view 
      class="card-list"
      scroll-y
      @scrolltolower="loadMore"
    >
      <view 
        v-for="card in showList"
        :key="card.id"
        class="card-item"
      >
        <image 
          class="card-cover"
          :src="card.cover || defaultCover"
          mode="aspectFill"
          @tap="previewCover(card.cover)"
        />
        <view class="card-info">
          <view class="header">
            <text class="card-name">{{ card.name }}</text>
            <uni-tag 
              :text="card.type | typeText"
              :type="card.type | typeColor"
              size="small"
            />
          </view>
          <view class="meta">
            <text class="stock">库存：{{ card.stock }}</text>
            <text class="validity">有效期：{{ card.validity }}</text>
          </view>
          <view class="footer">
            <text class="time">创建：{{ card.createTime | formatDate }}</text>
            <view class="actions">
              <button class="btn edit" @tap="showEditForm(card)">编辑</button>
              <button 
                class="btn status" 
                :class="card.status ? 'disable' : 'enable'"
                @tap="toggleStatus(card)"
              >
                {{ card.status ? '停用' : '启用' }}
              </button>
              <button 
                class="btn delete" 
                @tap="deleteCard(card)"
                v-if="adminInfo.role === '超级管理员'"
              >删除</button>
            </view>
          </view>
        </view>
      </view>

      <uni-load-more :status="loadingStatus"/>
    </scroll-view>

    <!-- 编辑弹窗 -->
    <uni-popup ref="editPopup" type="dialog">
      <uni-popup-dialog 
        mode="form" 
        :title="editForm.id ? '编辑卡片' : '新建卡片'"
        @confirm="submitForm"
      >
        <uni-forms :model="editForm">
          <uni-forms-item label="卡片名称" required>
            <uni-easyinput v-model="editForm.name" placeholder="请输入卡片名称"/>
          </uni-forms-item>
          <uni-forms-item label="卡片类型" required>
            <uni-data-select
              v-model="editForm.type"
              :localdata="typeOptions"
            />
          </uni-forms-item>
          <uni-forms-item label="封面图片">
            <uni-file-picker 
              v-model="editForm.cover"
              fileMediatype="image"
              limit="1"
              :imageStyles="{width: '200rpx', height: '200rpx'}"
            />
          </uni-forms-item>
          <uni-forms-item label="库存数量" required>
            <uni-number-box 
              v-model="editForm.stock"
              :min="0" 
              :max="9999"
            />
          </uni-forms-item>
          <uni-forms-item label="有效期">
            <uni-datetime-picker
              v-model="editForm.validity"
              type="daterange"
            />
          </uni-forms-item>
        </uni-forms>
      </uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
const generateCard = (() => {
  let id = 0
  const types = ['实体卡', '虚拟卡']
  return () => ({
    id: ++id,
    name: `纪念卡${id}`,
    type: types[Math.floor(Math.random()*2)],
    cover: Math.random() > 0.5 ? `https://picsum.photos/200/300?random=${id}` : '',
    stock: Math.floor(Math.random()*1000),
    validity: '2024-01-01 ~ 2024-12-31',
    status: Math.random() > 0.2,
    createTime: Date.now() - Math.floor(Math.random()*30*86400000)
  })
})()

export default {
  data() {
    return {
      adminInfo: { role: '超级管理员' },
      searchKey: '',
      filterType: 0,
      cardTypes: ['全部类型', '实体卡', '虚拟卡'],
      loadingStatus: 'more',
      page: 1,
      pageSize: 10,
      cardList: Array.from({length: 8}, generateCard),
      editForm: this.getDefaultForm(),
      typeOptions: [
        { value: '实体卡', text: '实体卡' },
        { value: '虚拟卡', text: '虚拟卡' }
      ],
      defaultCover: 'https://mp-1de2ab47-60cc-4717-bb0c-985e43d6d68e.cdn.bspapp.com/img/default-card.png'
    }
  },
  computed: {
    total() { return this.cardList.length },
    activeCount() { return this.cardList.filter(c => c.status).length },
    virtualCount() { return this.cardList.filter(c => c.type === '虚拟卡').length },
    showList() {
      return this.cardList.filter(c => {
        if(this.filterType === 1 && c.type !== '实体卡') return false
        if(this.filterType === 2 && c.type !== '虚拟卡') return false
        return c.name.includes(this.searchKey)
      }).slice(0, this.page * this.pageSize)
    }
  },
  filters: {
    typeText(value) {
      return value === '虚拟卡' ? '虚拟' : '实体'
    },
    typeColor(value) {
      return value === '虚拟卡' ? 'warning' : 'primary'
    },
    formatDate(timestamp) {
      const date = new Date(timestamp)
      return `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()}`
    }
  },
  methods: {
    getDefaultForm() {
      return {
        id: null,
        name: '',
        type: '实体卡',
        cover: '',
        stock: 0,
        validity: '',
        status: true
      }
    },
    showEditForm(card) {
      this.editForm = card ? {...card} : this.getDefaultForm()
      this.$refs.editPopup.open()
    },
    submitForm() {
      if (!this.validateForm()) return
      
      if(this.editForm.id) {
        const index = this.cardList.findIndex(c => c.id === this.editForm.id)
        this.cardList.splice(index, 1, this.editForm)
      } else {
        this.cardList.unshift({
          ...this.editForm,
          id: Date.now(),
          createTime: Date.now()
        })
      }
      this.$refs.editPopup.close()
      uni.showToast({ title: '操作成功' })
    },
    validateForm() {
      if(!this.editForm.name.trim()) {
        uni.showToast({ title: '请输入卡片名称', icon: 'none' })
        return false
      }
      if(this.editForm.stock < 0) {
        uni.showToast({ title: '库存不能为负数', icon: 'none' })
        return false
      }
      return true
    },
    toggleStatus(card) {
      card.status = !card.status
    },
    deleteCard(card) {
      uni.showModal({
        title: '确认删除',
        content: '确定要永久删除该卡片吗？',
        success: (res) => {
          if(res.confirm) {
            this.cardList = this.cardList.filter(c => c.id !== card.id)
          }
        }
      })
    },
    previewCover(url) {
      if(!url) return
      uni.previewImage({
        urls: [url],
        indicator: 'default'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.card-manage-container {
  padding: 20rpx;
}

.operation-bar {
  background: white;
  padding: 20rpx;
  border-radius: 12rpx;
  margin-bottom: 20rpx;

  .filter-row {
    display: flex;
    gap: 20rpx;
    margin-top: 20rpx;

    .filter-btn {
      flex: 1;
      padding: 10rpx 20rpx;
      background: #f8f9fa;
      border-radius: 8rpx;
    }

    .add-btn {
      background: #3498db;
      color: white;
      padding: 10rpx 20rpx;
    }
  }
}

.stats-scroll {
  white-space: nowrap;
  margin-bottom: 20rpx;

  .stats-card {
    display: inline-block;
    background: white;
    padding: 30rpx 50rpx;
    border-radius: 16rpx;
    margin-right: 20rpx;

    .stats-value {
      font-size: 40rpx;
      font-weight: bold;
      color: #2ecc71;
    }

    .stats-label {
      font-size: 28rpx;
      color: #7f8c8d;
    }
  }
}

.card-list {
  height: calc(100vh - 440rpx);
}

.card-item {
  display: flex;
  background: white;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  padding: 20rpx;

  .card-cover {
    width: 220rpx;
    height: 220rpx;
    border-radius: 12rpx;
    margin-right: 20rpx;
  }

  .card-info {
    flex: 1;

    .header {
      display: flex;
      align-items: center;
      margin-bottom: 15rpx;

      .card-name {
        font-size: 32rpx;
        font-weight: 500;
        margin-right: 20rpx;
      }
    }

    .meta {
      margin: 15rpx 0;
      display: flex;
      justify-content: space-between;

      .stock, .validity {
        font-size: 26rpx;
        color: #666;
      }
    }

    .footer {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .time {
        font-size: 24rpx;
        color: #95a5a6;
      }

      .actions {
        display: flex;
        gap: 10rpx;

        .btn {
          padding: 8rpx 20rpx;
          font-size: 26rpx;

          &.edit { background: #f1c40f; }
          &.enable { background: #2ecc71; }
          &.disable { background: #e74c3c; }
          &.delete { background: #95a5a6; }
        }
      }
    }
  }
}
</style>